var _echarts = require("echarts");

var zrUtil = _echarts.util;
var graphic = _echarts.graphic;
var matrix = _echarts.matrix;

/* global Microsoft.Maps.Map */
function BingMapCoordSys(bingmap, api) {
  this._bingmap = bingmap;
  this.dimensions = ['lng', 'lat'];
  this._mapOffset = [0, 0];
  this._api = api;
}

BingMapCoordSys.prototype.dimensions = ['lng', 'lat'];

BingMapCoordSys.prototype.setZoom = function (zoom) {
  this._zoom = zoom;
};

BingMapCoordSys.prototype.setCenter = function (center) {
  this._center = this._bingmap.tryLocationToPixel(new Microsoft.Maps.Location(center[1], center[0]))
};

BingMapCoordSys.prototype.setMapOffset = function (mapOffset) {
  this._mapOffset = mapOffset;
};

BingMapCoordSys.prototype.getBingMap = function () {
  return this._bingmap;
};

BingMapCoordSys.prototype.dataToPoint = function (data) {
  // console.log('dataToPoint', data)
  var lnglat = new Microsoft.Maps.Location(data[1], data[0]); // TODO mercator projection is toooooooo slow

  // 后面这个Microsoft.Maps.PixelReference.control参数不可少，否则转换出来的位置不对
  // 参考这个例子：http://www.bingmap.cn/guide/eb10959e-dafe-11e8-9ff7-d46d6d978bfa?module=doc
  // 也可以参考PixelReference的说明，http://www.bingmap.cn/guide/e0f16e5c-dafe-11e8-855d-d46d6d978bfa?module=doc
  // 这个Microsoft.Maps.PixelReference.control表示相对于地图控件的根元素的像素
  var px = this._bingmap.tryLocationToPixel(lnglat, Microsoft.Maps.PixelReference.control)
  var mapOffset = this._mapOffset;
  return [px.x - mapOffset[0], px.y - mapOffset[1]];
};

BingMapCoordSys.prototype.pointToData = function (pt) {
  // console.log('pointToData', pt)
  var mapOffset = this._mapOffset;

  var pt = this._bingmap.tryPixelToLocation({
    x: pt[0] + mapOffset[0],
    y: pt[1] + mapOffset[1]
  }, Microsoft.Maps.PixelReference.control);

  return [pt.longitude, pt.latitude];
};

BingMapCoordSys.prototype.getViewRect = function () {
  var api = this._api;
  return new graphic.BoundingRect(0, 0, api.getWidth(), api.getHeight());
};

BingMapCoordSys.prototype.getRoamTransform = function () {
  return matrix.create();
};

BingMapCoordSys.prototype.prepareCustoms = function (data) {
  var rect = this.getViewRect();
  return {
    coordSys: {
      // The name exposed to user is always 'cartesian2d' but not 'grid'.
      type: 'bingmap',
      x: rect.x,
      y: rect.y,
      width: rect.width,
      height: rect.height
    },
    api: {
      coord: zrUtil.bind(this.dataToPoint, this),
      size: zrUtil.bind(dataToCoordSize, this)
    }
  };
};

function dataToCoordSize(dataSize, dataItem) {
  dataItem = dataItem || [0, 0];
  return zrUtil.map([0, 1], function (dimIdx) {
    var val = dataItem[dimIdx];
    var halfSize = dataSize[dimIdx] / 2;
    var p1 = [];
    var p2 = [];
    p1[dimIdx] = val - halfSize;
    p2[dimIdx] = val + halfSize;
    p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
    return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  }, this);
}

var Overlay; // For deciding which dimensions to use when creating list data

BingMapCoordSys.dimensions = BingMapCoordSys.prototype.dimensions;

function createOverlayCtor() {
  function Overlay(root) {
    this._root = root;
  }

  Overlay.prototype = new Microsoft.Maps.CustomOverlay({ beneathLabels: true });
  Overlay.prototype.onAdd = function () {
    console.log('Overlay onAdd')
    this.setHtmlElement(this._root);
    //Logic to perform when adding overlay to map.
  };
  Overlay.prototype.onLoad = function () {
    console.log('Overlay onLoad')
    //Logic to perform after overlay has been added to the map.
  };
  Overlay.prototype.onRemove = function () {
    console.log('Overlay onRemove')
    //Logic to perform when overlay has been removed from the map.
  };
  return Overlay;
}

// 创建一个鼠标模拟事件，参考这里了：https://blog.csdn.net/honglei_zh/article/details/52291425
let createEvent = function (eventName, ofsx, ofsy) {
  var evt = document.createEvent('MouseEvents');
  evt.initMouseEvent(eventName, true, false, null, 0, 0, 0, ofsx, ofsy, false, false, false, false, 0, null);
  return evt;
};

BingMapCoordSys.create = function (ecModel, api) {
  var bingmapCoordSys;
  var root = api.getDom(); // TODO Dispose

  ecModel.eachComponent('bingmap', function (bingmapModel) {
    var painter = api.getZr().painter;
    var viewportRoot = painter.getViewportRoot();

    if (typeof Microsoft === 'undefined'
      || typeof Microsoft.Maps === 'undefined'
      || typeof Microsoft.Maps.Map === 'undefined') {
      throw new Error('It seems that Bing Map API has not been loaded completely yet.');
    }

    Overlay = Overlay || createOverlayCtor();
    if (bingmapCoordSys) {
      throw new Error('Only one bingmap component can exist');
    }

    if (!bingmapModel.__bingmap) {
      // Not support IE8
      var bingmapRoot = root.querySelector('.ec-extension-bingmap');

      if (bingmapRoot) {
        // Reset viewport left and top, which will be changed
        // in moving handler in BMapView
        viewportRoot.style.left = '0px';
        viewportRoot.style.top = '0px';
        viewportRoot.style.width = '100%';
        viewportRoot.style.height = '100%';
        root.removeChild(bingmapRoot);
      }

      bingmapRoot = document.createElement('div');
      bingmapRoot.style.cssText = 'width:100%;height:100%'; // Not support IE8
      bingmapRoot.className = 'ec-extension-bing-map';

      root.appendChild(bingmapRoot);
      var bingmap = bingmapModel.__bingmap = new Microsoft.Maps.Map(bingmapRoot);
      var mapOption = bingmapModel.get('mapOption') || {}; 
      bingmap.setOptions(mapOption)

      var overlay = new Overlay(viewportRoot);
      bingmap.layers.insert(overlay)
      console.log('after add overlay into layers', bingmap.layers)
      // 参考了bingmap的 Map的事件：http://www.bingmap.cn/guide/e02d19c6-dafe-11e8-a0a2-d46d6d978bfa?module=doc
      Microsoft.Maps.Events.addHandler(bingmap, 'mousemove',  (e)=>{ 
        // console.log('mouse move', e); 
        let mouseEvent = createEvent('mousemove', e.pageX, e.pageY)
        viewportRoot.dispatchEvent(mouseEvent)
      })
      Microsoft.Maps.Events.addHandler(bingmap, 'mousedown',  (e)=>{ 
        // console.log('mouse down', e); 
        let mouseEvent = createEvent('mousedown', e.pageX, e.pageY)
        viewportRoot.dispatchEvent(mouseEvent)
      })
      Microsoft.Maps.Events.addHandler(bingmap, 'mouseup',  (e)=>{ 
        // console.log('mouse up', e); 
        let mouseEvent = createEvent('mouseup', e.pageX, e.pageY)
        viewportRoot.dispatchEvent(mouseEvent)
      })
      painter.getViewportRootOffset = function () {
        return {
          offsetLeft: 0,
          offsetTop: 0
        };
      };
    }

    var bingmap = bingmapModel.__bingmap; // Set bingmap options
    // centerAndZoom before layout and render
    let viewOption = bingmapModel.get('viewOption')
    let {center, zoom} = viewOption
    // var center = bingmapModel.get('center');
    // var zoom = bingmapModel.get('zoom');
    var normalizedCenter = [
      center.lng != undefined ? center.lng : center[0],
      center.lat != undefined ? center.lat : center[1],
    ];
    console.log('normalizedCenter', center, normalizedCenter)

    if (center && zoom) {
      var bingmapCenter = bingmap.getCenter();
      var bingmapZoom = bingmap.getZoom();
      var centerOrZoomChanged = bingmapModel.centerOrZoomChanged([bingmapCenter.longitude, bingmapCenter.latitude], bingmapZoom);
      if (centerOrZoomChanged) {
        console.log('centerOrZoomChanged', normalizedCenter)
        var pt = new Microsoft.Maps.Location(normalizedCenter[1], normalizedCenter[0]);
        bingmap.setView({
          center: pt,
          zoom: zoom
        });
      }
    }

    bingmapCoordSys = new BingMapCoordSys(bingmap, api);
    bingmapCoordSys.setMapOffset(bingmapModel.__mapOffset || [0, 0]);
    bingmapCoordSys.setZoom(zoom);
    bingmapCoordSys.setCenter(center);
    bingmapModel.coordinateSystem = bingmapCoordSys;
  });
  ecModel.eachSeries(function (seriesModel) {
    if (seriesModel.get('coordinateSystem') === 'bingmap') {
      seriesModel.coordinateSystem = bingmapCoordSys;
    }
  });
};

var _default = BingMapCoordSys;
module.exports = _default;